import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'

const routes = [
  {
    path: '/',
    redirect: 'login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'Home',
    redirect: '/welcome',
    component: Home,
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: Welcome
      },
      {
        path: '/user/list',
        name: 'Users',
        component: Users
      }
    ]
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫 to 即将进入的路由； from 即将离开的路由； next 放行；
router.beforeEach((to, from, next) => {
  // 判断路由是否是登录页，如果是则放行
  if (to.path === '/login') {
    next()
  } else {
    // 判断用户是否已经登录
    if (window.sessionStorage.getItem('token')) {
      next()
    } else {
      // 没有登录就跳转到登录页面，query里面携带原请求的路径
      next({ path: '/login', query: { redirect: to.fullPath } })
    }
  }
})

export default router
